const jwt = require("jsonwebtoken");
const scrict = "youngam.cn"; //自定义的私钥

const EXPIRE = 60 * 60 * 24; // 这里设置24小时 token有效时长

// 生成token
function createToken(payload) {
  // 产生token
  payload.ctime = Date.now(); //token生成时间
  payload.exp = Math.floor(payload.ctime / 1000) * EXPIRE; //token过期时间
  return jwt.sign(payload, scrict);
}

// 验证token
function checkToken(token) {
  return new Promise((resolve, reject) => {
    jwt.verify(token, scrict, (err, data) => {
      if (err) {
        switch (err.message) {
          case "jwt expired": {
            reject({
              code: 1,
              msg: "token已过期",
            });
            break;
          }
          case "invalid token": {
            reject({
              code: 2,
              msg: "token无效",
            });
            break;
          }
          default: {
            reject({
              code: 9,
              msg: "token检验失败",
            });
          }
        }
      }
      resolve(data);
    });
  });
}

module.exports = {
  createToken,
  checkToken,
};
